package com.deyou.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.deyou.Constants;
import com.deyou.R;
import com.deyou.base.BaseActivity;
import com.deyou.callback.ServerApi;
import com.deyou.model.SimpleResponse;
import com.deyou.util.AESUtil;
import com.deyou.util.GlideImageLoader;
import com.deyou.util.Logger;
import com.deyou.util.SPUtils;
import com.deyou.util.Urls;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;
import com.yanzhenjie.album.Album;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class UploadVerifyDataActivity extends BaseActivity {

    @BindView(R.id.tv_mid_title)
    TextView tvMidTitle;
    @BindView(R.id.edt_name)
    EditText edtName;
    @BindView(R.id.edt_card_num)
    EditText edtCardNum;
    @BindView(R.id.iv_card_front)
    ImageView ivCardFront;
    @BindView(R.id.iv_card_reverse)
    ImageView ivCardReverse;
    @BindView(R.id.btn_submit_data)
    TextView btnSubmitData;
    @BindView(R.id.iv_front_upload_complete)
    ImageView ivFrontUploadComplete;
    @BindView(R.id.tv_front_uploading_status)
    TextView tvFrontUploadingStatus;
    @BindView(R.id.front_uploading_progress)
    ProgressBar frontUploadingProgress;
    @BindView(R.id.front_card_progress_layout)
    LinearLayout frontCardProgressLayout;
    @BindView(R.id.front_card_layout)
    RelativeLayout frontCardLayout;
    @BindView(R.id.iv_reverse_upload_complete)
    ImageView ivReverseUploadComplete;
    @BindView(R.id.tv_reverse_uploading_status)
    TextView tvReverseUploadingStatus;
    @BindView(R.id.reverse_uploading_progress)
    ProgressBar reverseUploadingProgress;
    @BindView(R.id.reverse_card_progress_layout)
    LinearLayout reverseCardProgressLayout;
    @BindView(R.id.reverse_card_layout)
    RelativeLayout reverseCardLayout;

    private ArrayList<String> mImageList = new ArrayList<>();
    private ArrayList<String> mImageList1 = new ArrayList<>();
    private String frontImgUrl, reverseImgUrl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload_verify_data);
        ButterKnife.bind(this);
    }

    @Override
    protected boolean translucentStatusBar() {
        return super.translucentStatusBar();
    }

    @Override
    protected void onStart() {
        super.onStart();
        tvMidTitle.setText("实名认证");
    }

    @OnClick({R.id.iv_left_back, R.id.front_card_layout, R.id.reverse_card_layout, R.id.btn_submit_data})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_left_back:
                finish();
                break;
            case R.id.front_card_layout:
                callAlbumFront();
                break;
            case R.id.reverse_card_layout:
                callAlbumReverse();
                break;
            case R.id.btn_submit_data:
                if (TextUtils.isEmpty(edtName.getText().toString())){
                    showToast("请填写实名认证的名字");
                    return;
                }
                if (TextUtils.isEmpty(edtCardNum.getText().toString())){
                    showToast("请填写实名认证的证件号");
                    return;
                }
                if (TextUtils.isEmpty(frontImgUrl)){
                    showToast("请上传实名认证的正面照片");
                    return;
                }
                if (TextUtils.isEmpty(reverseImgUrl)){
                    showToast("请上传实名认证的反面照片");
                    return;
                }
                uploadVerifyData();
                break;
        }
    }

    private void callAlbumFront() {
        Album.albumRadio(this)
                .toolBarColor(getResources().getColor(R.color.color_FF832D)) // Toolbar 颜色，默认蓝色。
                .statusBarColor(getResources().getColor(R.color.color_FF832D)) // StatusBar 颜色，默认蓝色。
//                .navigationBarColor(navigationBarColor) // NavigationBar 颜色，默认黑色，建议使用默认。
                .title("图库") // 配置title。
//                .selectCount(1) // 最多选择几张图片。
                .columnCount(3) // 相册展示列数，默认是2列。
                .camera(true) // 是否有拍照功能。
//                .checkedList(mImageList) // 已经选择过得图片，相册会自动选中选过的图片，并计数。
                .start(999);
    }

    private void callAlbumReverse() {
        Album.albumRadio(this)
                .toolBarColor(getResources().getColor(R.color.color_FF832D)) // Toolbar 颜色，默认蓝色。
                .statusBarColor(getResources().getColor(R.color.color_FF832D)) // StatusBar 颜色，默认蓝色。
//                .navigationBarColor(navigationBarColor) // NavigationBar 颜色，默认黑色，建议使用默认。
                .title("图库") // 配置title。
//                .selectCount(1) // 最多选择几张图片。
                .columnCount(3) // 相册展示列数，默认是2列。
                .camera(true) // 是否有拍照功能。
//                .checkedList(mImageList1) // 已经选择过得图片，相册会自动选中选过的图片，并计数。
                .start(9999);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 999) {
            if (resultCode == RESULT_OK) { // Successfully.
                mImageList = Album.parseResult(data);
                if (null != mImageList && mImageList.size() > 0) {
                    new GlideImageLoader().displayImage(this, mImageList.get(0), ivCardFront);
                    frontCardProgressLayout.setVisibility(View.VISIBLE);
                    frontUploadingProgress.setVisibility(View.VISIBLE);
                    tvFrontUploadingStatus.setVisibility(View.VISIBLE);
                    ivFrontUploadComplete.setVisibility(View.GONE);
                    uploadFrontVerifyImg();
                } else {
                    new GlideImageLoader().displayImage(this, R.drawable.bg_default_photo, ivCardFront);
                }
            } else if (resultCode == RESULT_CANCELED) { // User canceled.
                // 用户取消了操作。
            }
        } else if (requestCode == 9999) {
            if (resultCode == RESULT_OK) { // Successfully.
                mImageList1 = Album.parseResult(data);
                if (null != mImageList1 && mImageList1.size() > 0) {
                    reverseCardProgressLayout.setVisibility(View.VISIBLE);
                    reverseUploadingProgress.setVisibility(View.VISIBLE);
                    tvReverseUploadingStatus.setVisibility(View.VISIBLE);
                    ivReverseUploadComplete.setVisibility(View.GONE);
                    uploadReverseVerifyImg();
                    new GlideImageLoader().displayImage(this, mImageList1.get(0), ivCardReverse);
                } else {
                    new GlideImageLoader().displayImage(this, R.drawable.bg_default_photo, ivCardReverse);
                }
            } else if (resultCode == RESULT_CANCELED) { // User canceled.
                // 用户取消了操作。
            }
        }
    }

    /**
     * 上传正面认证照片
     *
     */
    private void uploadFrontVerifyImg(){
        final ArrayList<File> files = new ArrayList<>();
        if (mImageList != null && mImageList.size() > 0) {
            for (int i = 0; i < mImageList.size(); i++) {
                files.add(new File(mImageList.get(i)));
            }
        }
        Observable.create(new ObservableOnSubscribe<Progress>() {
            @Override
            public void subscribe(@NonNull final ObservableEmitter<Progress> e) throws Exception {
                OkGo.<String>post(Urls.uploadImg)//
                        .tag(this)//
                        .addFileParams("file", files)//
                        .execute(new StringCallback() {
                            @Override
                            public void onSuccess(Response<String> response) {
                                e.onComplete();
                                SimpleResponse resp = new Gson().fromJson(response.body(), SimpleResponse.class);
                                if (resp.code == 1 && !TextUtils.isEmpty(resp.data))
                                    frontImgUrl = resp.data;
                                else
                                    frontImgUrl = "";
                            }

                            @Override
                            public void onError(Response<String> response) {
                                e.onError(response.getException());
                            }

                            @Override
                            public void uploadProgress(Progress progress) {
                                e.onNext(progress);
                            }
                        });
            }
        })//
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        tvFrontUploadingStatus.setText("正在上传中");
                        frontUploadingProgress.setMax(10000);
                        frontUploadingProgress.setProgress(0);
                    }
                })//
                .observeOn(AndroidSchedulers.mainThread())//
                .subscribe(new Observer<Progress>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(@NonNull Progress progress) {
                       Logger.i(Logger.LOGTAG + "uploadProgress: " + progress);
                        frontUploadingProgress.setMax(10000);
                        frontUploadingProgress.setProgress((int) (progress.fraction * 10000));
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        e.printStackTrace();
                        tvFrontUploadingStatus.setText("上传失败");
                        showToast("上传出错  \n" + e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        ivFrontUploadComplete.setVisibility(View.VISIBLE);
                        frontUploadingProgress.setVisibility(View.GONE);
                        tvFrontUploadingStatus.setText("上传完成");
                    }
                });
    }

    /**
     * 上传反面认证照片
     *
     */
    private void uploadReverseVerifyImg(){
        final ArrayList<File> files = new ArrayList<>();
        if (mImageList1 != null && mImageList1.size() > 0) {
            for (int i = 0; i < mImageList1.size(); i++) {
                files.add(new File(mImageList1.get(i)));
            }
        }
        Observable.create(new ObservableOnSubscribe<Progress>() {
            @Override
            public void subscribe(@NonNull final ObservableEmitter<Progress> e) throws Exception {
                OkGo.<String>post(Urls.uploadImg)//
                        .tag(this)//
                        .addFileParams("file", files)//
                        .execute(new StringCallback() {
                            @Override
                            public void onSuccess(Response<String> response) {
                                e.onComplete();
                                SimpleResponse resp = new Gson().fromJson(response.body(), SimpleResponse.class);
                                if (resp.code == 1 && !TextUtils.isEmpty(resp.data))
                                    reverseImgUrl = resp.data;
                                else
                                    reverseImgUrl = "";
                            }

                            @Override
                            public void onError(Response<String> response) {
                                e.onError(response.getException());
                            }

                            @Override
                            public void uploadProgress(Progress progress) {
                                e.onNext(progress);
                            }
                        });
            }
        })//
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        tvReverseUploadingStatus.setText("正在上传中");
                        reverseUploadingProgress.setMax(10000);
                        reverseUploadingProgress.setProgress(0);
                    }
                })//
                .observeOn(AndroidSchedulers.mainThread())//
                .subscribe(new Observer<Progress>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(@NonNull Progress progress) {
                        Logger.i(Logger.LOGTAG + "uploadProgress: " + progress);
                        reverseUploadingProgress.setMax(10000);
                        reverseUploadingProgress.setProgress((int) (progress.fraction * 10000));
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        e.printStackTrace();
                        tvReverseUploadingStatus.setText("上传失败");
                        showToast("上传出错  \n" + e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        ivReverseUploadComplete.setVisibility(View.VISIBLE);
                        reverseUploadingProgress.setVisibility(View.GONE);
                        tvReverseUploadingStatus.setText("上传完成");
                    }
                });
    }

    private void uploadVerifyData(){
        JSONObject object = new JSONObject();
        try {
            object.put("userRealname", edtName.getText().toString());
            object.put("userCard", edtCardNum.getText().toString());
            object.put("userCardPic", frontImgUrl + "," + reverseImgUrl + ",");
            object.put("userId", SPUtils.getStringByKey(UploadVerifyDataActivity.this, Constants.UserId));
            String paramJson = object.toString();

            ServerApi.getString(Urls.uploadVerifyData, "", AESUtil.encrypt(paramJson))//
                    .subscribeOn(Schedulers.io())//
                    .doOnSubscribe(new Consumer<Disposable>() {
                        @Override
                        public void accept(@io.reactivex.annotations.NonNull Disposable disposable) throws Exception {
                            showLoading("上传认证资料中...");
                        }
                    })//
                    .observeOn(AndroidSchedulers.mainThread())  //
                    .subscribe(new Observer<String>() {
                        @Override
                        public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {
                            addDisposable(d);
                        }

                        @Override
                        public void onNext(@io.reactivex.annotations.NonNull String s) {
                            SimpleResponse resp = new Gson().fromJson(s, SimpleResponse.class);
                            if (null != resp && resp.code == 1){
                                setResult(1);
                                finish();
                            } else {
                                showToast(resp.msg);
                            }
                        }

                        @Override
                        public void onError(@io.reactivex.annotations.NonNull Throwable e) {
                            e.printStackTrace();            //请求失败
                            showToast("认证资料上传失败");
                        }

                        @Override
                        public void onComplete() {
                            dismissLoading();
                        }
                    });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
